# -*- coding: UTF-8 -*-
"""
@Author:mengying
@File:weixin_SnedMessage.py
@Time:2021-05-25
@Email:a652044581@qq.com
@Features: 企业微信机器人的消息通知
"""

import requests
import base64
import hashlib
from config import config


class WxRobot:
    def __init__(self, webhook=None, msg=None, file_path=None):
        self.msg = msg
        self.bot = webhook or config.WEBHOOK
        self.file_path = file_path

    def send_text(self):
        url = f"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={self.bot}"
        headers = {"Content-Type": "text/plain"}
        data = {
            "msgtype": "text",
            "text": {
                "content": self.msg,
            }
        }
        resp = requests.post(url, headers=headers, json=data)
        return resp

    def send_markdown(self):
        url = f"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={self.bot}"
        data = {
            "msgtype": "markdown",
            "markdown": {"content": self.msg}
        }
        resp = requests.post(url, json=data).text
        return resp

    def send_file(self):
        file_url = f"https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?key={self.bot}&type=file"
        file = {'file': open(self.file_path, 'rb')}
        result = requests.post(file_url, files=file)
        file_id = eval(result.text)['media_id']
        url = f"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={self.bot}"
        data = {
            "msgtype": "file",
            "file": {"media_id": file_id, }
        }
        resp = requests.post(url, json=data).text
        return resp

    def send_img(self):
        with open(self.file_path, "rb") as f:
            base64_data = base64.b64encode(f.read())
        file = open(self.file_path, "rb")
        md = hashlib.md5()
        md.update(file.read())
        res1 = md.hexdigest()
        url = f"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={self.bot}"
        headers = {"Content-Type": "text/plain"}
        data = {
            "msgtype": "image",
            "image": {
                "base64": base64_data.decode('utf-8'),
                "md5": res1
            }
        }
        resp = requests.post(url, headers=headers, json=data).text
        return resp


if __name__ == '__main__':
    bot = "webhook_key"
    msg = "msg"
    robot = WxRobot(webhook=bot, msg=msg)
    robot.send_text()
